package dev.common.base;

import com.alibaba.fastjson.JSONObject;
import dev.common.utils.WebUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @program: JoyDev
 * @description: 基类控制器
 * @author: MR.C
 * @create: 2018-02-08 14:48
 **/
public class BaseController {
    protected Logger logger = Logger.getLogger(BaseController.class);

    /**
     * @Description: 返回响应信息，不携带额外参数
     * @Param: [success, msg]
     * @return: dev.common.base.ResModel
     * @Author: Mr.Chen
     * @Date: 2018/2/8 下午2:56
     */
    protected ResModel sendMessage2Web(Boolean success, String msg) {
        ResModel res = new ResModel();
        res.setCode(success ? 0 : -1);
        res.setMsg(msg);
        res.setSuccess(success);
        return res;
    }

    /**
     * 返回成功带有数据的处理结果
     *
     * @param msg  成功信息
     * @param data 相应数据
     * @return
     * @author chenjy
     * @time 2017年10月14日 下午9:35:18
     */
    public ResModel sendSuccess2Web(String msg, Object data) {
        ResModel result = new ResModel();
        result.setMsg(msg);
        result.setCode(0);
        result.setSuccess(true);
        result.setData(data);
        return result;
    }

    /**
     * 返回失败带有数据的处理结果
     *
     * @param msg  失败信息
     * @param data 相应数据
     * @return
     * @author chenjy
     * @time 2017年10月14日 下午9:37:17
     * @description
     */
    public ResModel sendFalse2Web(String msg, Object data) {
        ResModel result = new ResModel();
        result.setSuccess(false);
        result.setCode(-1);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }


    /**
     * 异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResModel exceptionHandler(HttpServletRequest request, Exception ex) throws Exception {
        Map<String, Object> paramMap = WebUtils.getParamMap(request);
        logger.error("访问用户：" + WebUtils.getCurrUser());
        logger.error("请求接口：" + request.getServletPath());
        logger.error("请求参数：" + JSONObject.toJSON(paramMap));
        logger.error("异常信息：" + ex.getMessage());
        logger.error("异常跟踪：", ex);

        ResModel res = new ResModel();
        res.setSuccess(false);
        res.setMsg(ex.getMessage());
        res.setCode(-1);
        return res;
    }

    protected void notNull(Object param, String msg) {
        if (null == param)
            throw new IllegalArgumentException(msg);
    }
}
